/**
 * 
 */
package info.niwota.web.apache;

import info.niwota.web.io.CounterInputStream;

import java.io.IOException;
import java.io.OutputStream;

import x.org.apache.http.entity.InputStreamEntity;

/**
 * Set content length when done writing
 * 
 * @author qiangli
 *
 */
public class MyInputStreamEntity extends InputStreamEntity {
	private static final long ALL = -1;
	
	private CounterInputStream in;
	private boolean close;
	private long length = -1;
	
	public MyInputStreamEntity(CounterInputStream in, boolean close) {
		super(in, ALL);
		
		this.in = in;
		this.close = close;
	}

	@Override
	public void writeTo(OutputStream outstream) throws IOException {
		super.writeTo(outstream);
		length = in.getCounter();
		
		if (close) {
			in.close();
		}
	}

	@Override
	public long getContentLength() {
		return this.length;
	}	
}
